<?php

namespace App\B2BProject\Custom\Purchaser;

use App\B2BProject\Custom\Business\Goods;
use App\B2BProject\Exception\UserTypeException;
use Illuminate\Database\Eloquent\Model;

class ShoppingCart extends Model
{
    protected $guarded = ['id', 'created_at', 'update_at'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function purchaser()
    {
        return $this->belongsTo('App\B2BProject\Custom\Purchaser', 'member_id', 'id');
    }

    /**
     * 获取购物车对应商品项
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function goods()
    {
        return $this->belongsTo('App\B2BProject\Custom\Business\Goods', 'goods_id', 'id');
    }

    /**
     * 向购物车添加商品
     *
     * @param      $goods
     * @param int  $amount
     * @param null $specId
     * @param null $message
     *
     * @return ShoppingCart
     *
     * @throws \BadMethodCallException 商品不可添加入购物车
     * @throws \InvalidArgumentException 添加商品进购物车时必要的参数缺失
     * @throws UserTypeException 用户类型不匹配
     */
    public static function addToCart($goods, $amount = 1, $specId = null, $message = null)
    {
        if (\Auth::user()->isPurchaser()) {
            $member_id = \Auth::user()->id;

            return \DB::transaction(function () use ($goods, $amount, $specId, $message, $member_id) {
                $record = new static;

                // TODO 【注意】现在简单粗暴的直接设置 ID 以减少不必要的前期麻烦，后期肯定需要改动为利用关联模型实现！
                if (!($goods instanceof Goods)) {
                    $goods = Goods::findOrFail($goods);
                }

                // 判断当前商品是否是可售卖的
                if (!$goods->sell_status) {
                    throw new \BadMethodCallException('当前商品不可购买（可能被删除或禁售）');
                }

                $record->goods_id = $goods->id;

                if ($goods->hasSpecification()) {
                    if (is_null($specId)) {
                        throw new \InvalidArgumentException('当前商品必须选择规格');
                    }

                    $spec = $goods->goodsSpecification()->whereId($specId)->firstOrFail();

                    $record->goods_spec_id = $spec->id;
                }

                $record->amount    = $amount;
                $record->member_id = $member_id;


                $record->save();

                return $record;
            });
        } else {
            throw new UserTypeException;
        }
    }
}
